package com.ying.dogying.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.ying.dogying.entity.Const;
import com.ying.dogying.entity.ImUser;
import com.ying.dogying.im.dto.lastDto.ImLastMessage;
import com.ying.dogying.service.ImChatService;
import com.ying.dogying.shiro.AccountProfileDto;
import com.ying.dogying.utils.RandomValueUtil;
import com.ying.dogying.utils.RedisUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("imChatService")
public class ImChatServiceImpl implements ImChatService {

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public ImUser getCurrentUser() {

        AccountProfileDto profile = (AccountProfileDto) SecurityUtils.getSubject().getPrincipal();
        ImUser imUser = new ImUser();
        if (null != profile) {
            imUser.setId(profile.getId());
            imUser.setUsername(profile.getUsername());
            imUser.setAvatar(profile.getAvatar());
            imUser.setStatus(1);
            return imUser;
        }
        // 匿名用户处理
        Long personId = (Long) SecurityUtils.getSubject().getSession().getAttribute("personId");
        imUser.setId(personId != null ? personId : RandomUtil.randomLong());
        imUser.setUsername(RandomValueUtil.getChineseName());
        imUser.setSign("never give up!");
        imUser.setAvatar("http://tp1.sinaimg.cn/5619439268/180/40030060651/1");
        imUser.setStatus(1);
        SecurityUtils.getSubject().getSession().setAttribute("personId", imUser.getId());
        return imUser;
    }

    @Override
    public void setGroupHistoryMessage(ImLastMessage imLastMessage) {
        redisUtils.lSet(Const.IM_GROUP_HISTORY_MSG_KEY, imLastMessage, 24 * 60 * 60);
    }

    @Override
    public List<Object> getGroupHistoryMessage(int count) {
        long length = redisUtils.lGetListSize(Const.IM_GROUP_HISTORY_MSG_KEY);
        // 来吧~展示 最后20条历史消息
        return redisUtils.lGet(Const.IM_GROUP_HISTORY_MSG_KEY, length - count < 0 ? 0 : length - count, length);
    }
}
